import React, { useState } from 'react'
import http from '../utils/request'
import { Button, message, Radio } from 'antd';
// 导入useNavigate
import { useNavigate } from 'react-router-dom';
//
import { ArrowLeft } from '@nutui/icons-react'
import { NavBar, } from '@nutui/nutui-react'
export default function Face({ }) {
  const [isVideo, setIsVideo] = useState(false)
  const [isRadioChecked, setIsRadioChecked] = useState(false)
  const [messageApi, contextHolder] = message.useMessage();
  // navigate
  const nav = useNavigate()
  // 处理Radio选中状态
  const handleRadioChange = (e) => {
    setIsRadioChecked(e.target.checked);
  };
  async function startCamera() {

    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true
      });
      const videoElement = document.getElementById('video');
      videoElement.srcObject = stream;
    } catch (error) {
      console.error('无法访问摄像头:', error);
      if (error.name === 'NotAllowedError') {
        alert('您拒绝了摄像头权限，无法进行识别。');
      } else {
        alert('摄像头访问出错，请检查设备。');
      }
    }
  }
  function captureFrame() {
    const video = document.getElementById('video');
    const canvas = document.createElement('canvas');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    const imageData = canvas.toDataURL('image/jpeg')
    return imageData;
  }



  async function startCameraAndSearch() {
    console.log(isRadioChecked)
    if (isRadioChecked) {
      console.log(456)
      setIsVideo(true)
      await startCamera();
      setTimeout(async () => {
        const imageData = captureFrame();
        console.log(imageData, "图片21")
        let res = await http.post('/faceLogin', { imageData })
        let { code, msg, id, accessToken, refreshToken } = res.data
        if (code == 200) {
          messageApi.open({
            type: 'success',
            content: msg,
          });
          // 跳转到首页
          nav("/shou/index")
          sessionStorage.setItem('id', id)
          localStorage.setItem('accessToken', accessToken); // 存储访问令牌
          localStorage.setItem('refreshToken', refreshToken); // 存储刷新令牌
        } else {

          messageApi.open({
            type: 'error',
            content: msg,
          });
        }
      }, 5000);
    } else {
      messageApi.open({
        type: 'error',
        content: '请先阅读并选中用户隐私政策',
      });
    }
  }



  // 新增取消人脸识别操作的函数
  function cancelFaceRecognition() {
    const videoElement = document.getElementById('video');
    if (videoElement.srcObject) {
      const stream = videoElement.srcObject;
      const tracks = stream.getTracks();
      tracks.forEach((track) => track.stop());
      videoElement.srcObject = null;
    }
    setIsVideo(false);
  }

  return (
    <>
      {contextHolder}
      <NavBar
        back={
          <>
            <ArrowLeft />
          </>
        }
        onBackClick={() => nav("/app/login")}
      ></NavBar>



      <div className='face-box'>
        <div style={{ display: isVideo ? 'block' : 'none' }}>
          <video id="video" style={{ width: "100%" }} autoPlay className='face-video'></video>
          <p>请正对手机，将人脸移入检测框</p>
        </div>
        <div className='placeholder-box' style={{ display: isVideo ? 'none' : 'block' }}>
          <div style={{ textAlign: "center" }}>
            <img src="https://tse1-mm.cn.bing.net/th/id/OIP-C.VQie14Lx7VZjKuJjCRiBFwHaFR?rs=1&pid=ImgDetMain" alt="" style={{ width: "160px", height: "150px" }} />
          </div>

          <p style={{ paddingLeft: "30px" }}>您即将进行人脸识别验证</p>
        </div>
        <div style={{ paddingLeft: "40px" }}>
          <Radio onChange={handleRadioChange}><span className='content'>我已阅读用户隐私政策</span></Radio>
        </div>

       <div style={{textAlign:"center"}}>
        
       <Button type="primary" size="large" block
          onClick={startCameraAndSearch} style={{ display: isVideo ? 'block' : 'inline', width: '250px', textAlign: "center" }}>
          开始验证
        </Button>
       </div>
        {isVideo && (
          <Button
            type="link"
            onClick={cancelFaceRecognition}
            style={{ display: 'inline', marginLeft: '10px' }}
          >
            取消识别
          </Button>
        )}
      </div>

    </>
  )
}